package com.laosg.spring.basic;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * <p>description: some thing </p>
 *
 * @author kevinruan@pano.im
 * @date 2020/6/21
 */
public class BeanFactory {
    private static Properties env=new Properties();//启动的时候，读取进来
    static {
        InputStream resourceAsStream = BeanFactory.class.getResourceAsStream("/application.properties");
        try {
            env.load(resourceAsStream);
            resourceAsStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 这里也就引出了耦合-》 使用了构造器创建对象
     * - 我们也可以使用反射的方式完成创建对象
     * - Class clazz = Class.forName("com.laosg.spring.basic.UserServiceImpl");
     *   UserService us = (UserService) clazz;
     * @return
     */
    public static UserService getUserService() {
//        return new UserServiceImpl();
        UserService us=null;
        try {
            Class aClazz = Class.forName(env.getProperty("userService"));
            us = (UserService) aClazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return us;
    }

    public static UserDao getUserDao() {
        UserDao us=null;
        try {
            Class aClazz = Class.forName(env.getProperty("userDao"));
            us = (UserDao) aClazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return us;
    }

    //有大量的代码冗余，这里最好封装通用的方法

    public static Object getBean(String service) {
        Object us=null;
        try {
            Class aClazz = Class.forName(env.getProperty(service));
            us =  aClazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return us;
    }
}
